package bit.client.model;

import org.jsoup.Connection;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.regex.*;

public class ExamGetter {
    private BitBasic basic;
    private URL functionUrl;
    Document doc;

    ExamGetter(BitBasic basic) throws IOException {
        this.basic = basic;
        functionUrl = basic.examURL;
        Connection.Response response = basic.get(functionUrl);
        doc = response.parse();
    }

    public List<Exam> getExam() {
        Elements trlist = doc.select("#DataGrid1 tbody").first().select("tr:not(.datagridhead)");
        List<Exam> rtval = new ArrayList<>();
        for (Element tr : trlist) {
            List<String> tdlist = tr.select("td").eachText();
            if (tdlist.get(4).trim().length() == 1) continue;
            rtval.add(new Exam(tdlist.get(1), tdlist.get(3), tdlist.get(4), tdlist.get(6)));
        }
        return rtval;
    }

    static class Exam {
        String name;
        Calendar time;
        String place;
        int seat;

        Exam(String name, String rawTime, String place, String seat) {
            this.name = name;
            this.place = place;
            this.seat = Integer.parseInt(seat);
            Pattern pattern = Pattern.compile("第\\d+周周\\d+\\((\\d+)-(\\d+)-(\\d+)\\) (\\d+):(\\d+)");
            Matcher result = pattern.matcher(rawTime);
            if (result.find()) {
                int year = Integer.parseInt(result.group(1));
                int month = Integer.parseInt(result.group(2));
                int day = Integer.parseInt(result.group(3));
                int hour = Integer.parseInt(result.group(4));
                int min = Integer.parseInt(result.group(5));
                Calendar cal = Calendar.getInstance();
                cal.set(year, month - 1, day, hour, min);
                time = cal;
            }
        }
    }
}
